package com.eig.auth.service;


import com.eig.auth.feign.SystemFeign;
import com.eig.common.entity.AclPermission;
import com.eig.common.entity.AclUser;
import com.eig.common.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: eight-education-cloud
 * @description:
 * @author:
 * @create:
 **/
@Service
public class MyUserService implements UserDetailsService {

    @Autowired
    private SystemFeign systemFeign;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //根据账户查询用户信息
        Result<AclUser> result = systemFeign.getByName(s);
        if(result!=null && result.getData()!=null){
            AclUser aclUser =  result.getData();

            Result<List<AclPermission>> result1 = systemFeign.getByUserid(aclUser.getId());
            if(result1!=null){

                List<AclPermission> permissions =  result1.getData();

                List<SimpleGrantedAuthority> authorities=permissions.stream()
                                                   //过滤掉不满足条件的元素
                                                  .filter(item->item.getPermissionValue()!=null)
                                                    //把集合中的元素类型转化为SimpleGrantedAuthority类型
                                                  .map(item->new SimpleGrantedAuthority(item.getPermissionValue()))
                                                   .collect(Collectors.toList());
                User user = new User(aclUser.getUsername(),aclUser.getPassword(),authorities);
                return user;
            }
        }

        return null;
    }
}
